import axios from 'axios';
import { message } from 'antd';
import store from 'storejs';
// let baseUrl = process.env.REACT_APP_BASEURL;
// console.log('baseUrl: ', baseUrl);

const instance = axios.create({
  // baseURL: baseUrl,
  timeout: 10000000,
});

// 请求拦截
instance.interceptors.request.use(
  async function (config) {
    const userInfo = store.get('userInfo');
    const zhima = userInfo?.zhima;
    const token = localStorage.getItem('token') && JSON.parse(localStorage.getItem('token') || '');
    config.headers['Authorization'] = `Bearer ${token}`; // 获取token
    config.headers['Accept'] = 'application/json';
    config.headers['Content-Type'] = 'application/json';
    config.headers['Gate-key'] = zhima?.key;
    config.headers['Gate-secret'] = zhima?.secret;
    // 下单添加渠道，佣金
    config.headers['X-Gate-Channel-Id'] = 'qidian';
    return config;
  },
  function (error) {
    console.log('请求失败拦截-err: ', error);
    return Promise.reject(error);
  },
);

// 响应拦截
instance.interceptors.response.use(
  function (response: any) {
    // console.log('响应拦截-suc');
    return response?.data;
  },
  function (error) {
    console.log('响应拦截-err', error);
    if (error?.status === 401) {
      message.error('登录已失效，请重新登录');
      localStorage.clear();
      window.location.href = '/login';
    }
    if (error?.status === 404) {
      // message.error('接口不存在');
    } else if (error?.status === 400) {
      // gate接口
      // message.error(error?.response?.data?.message || '服务器错误');
    }
    return Promise.resolve(error?.response);
  },
);

export const get = (url: string, params = {}) => instance.get(url, { params });
export const post = (url: string, data = {}) => instance.post(url, data);
export const put = (url: string, data = {}) => instance.put(url, data);
